package com.sdgakj.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class HTTPUtil {
	
	
	private static final Logger log = Logger.getLogger(HTTPUtil.class);
	
	
	private static int TIMEOUT_CONNECTION = 5000;
	private static int TIMEOUT_READ = 30000;
	
	public static String saveUploadFile(String rootDir, String fileParameterName,
			String fileSuffix, String filePrefix, HttpServletRequest request){
		String result = null;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile(fileParameterName);
		if(file == null){
			return result;
		}
		//save temporary file
		String localFilePath = rootDir;
		String localFile = file.getOriginalFilename();
		if(localFile == "" || localFile == null){
			return result;
		}
		InputStream ins = null;
		OutputStream fos = null;
		try{
			request.setCharacterEncoding("utf-8");
			ins = file.getInputStream();
			String localFileName = localFile.substring(
											file.getOriginalFilename().lastIndexOf("."), 
											file.getOriginalFilename().length()); 
			if(filePrefix == null){
				filePrefix = "";
			}
			result = "/" + filePrefix + DateUtil.formatDateToString(new Date(), "yyyyMMddHHmmss") + localFileName;
			localFileName = localFilePath + "/" + filePrefix + DateUtil.formatDateToString(new Date(), "yyyyMMddHHmmss") + localFileName;
			fos = new FileOutputStream(localFileName);
			try{
				int readed = 0;
				byte[] buffer = new byte[8192];
				while((readed = ins.read(buffer, 0, 8192)) != -1){
					fos.write(buffer, 0, readed);
				}
			}catch(Exception e){
				e.printStackTrace();
				result = null;
			}
		}catch(Exception e){
			e.printStackTrace();
			result = null;
		}finally{
			if(ins != null){
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				ins=null;
			}
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				fos = null;
			}
		}
		return result; 
	}
	
    public static List<String> readFileByLines(String fileName) {
    	List<String> list = new LinkedList<String>();
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
            	list.add(tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return list;
    }
    
    public static String saveZipEntryFile(String rootDir, ZipFile zipfile, ZipEntry zipEntry,
			String fileSuffix, String filePrefix){
		String result = null;
		//save temporary file
		String localFilePath = rootDir;
		String localFile = zipEntry.getName();
		localFile = localFile.replace('\\', '/');
		if(localFile == "" || localFile == null){
			return result;
		}
		InputStream ins = null;
		OutputStream fos = null;
		try{
			ins = zipfile.getInputStream(zipEntry);
			String localFileName = localFile.substring(
												localFile.lastIndexOf("."), 
												localFile.length()); 
			if(filePrefix == null){
				filePrefix = "";
			}
			result = "/" + filePrefix + DateUtil.formatDateToString(new Date(), "yyyyMMddHHmmss") + localFileName;
			localFileName = localFilePath + "/" + filePrefix + DateUtil.formatDateToString(new Date(), "yyyyMMddHHmmss") + localFileName;
			fos = new FileOutputStream(localFileName);
			try{
				int readed = 0;
				byte[] buffer = new byte[8192];
				while((readed = ins.read(buffer, 0, 8192)) != -1){
					fos.write(buffer, 0, readed);
				}
			}catch(Exception e){
				e.printStackTrace();
				result = null;
			}
		}catch(Exception e){
			e.printStackTrace();
			result = null;
		}finally{
			if(ins != null){
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				ins=null;
			}
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				fos = null;
			}
		}
		return result; 
	}
    
    public static String getIpAddr(HttpServletRequest request) {    
        String ip = request.getHeader("x-forwarded-for");    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
           ip = request.getHeader("Proxy-Client-IP");    
       }    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
           ip = request.getHeader("WL-Proxy-Client-IP");    
        }    
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getRemoteAddr();    
       }    
       return ip;    
    } 
    public static String saveUploadFileKeepFileName(String rootDir, String fileParameterName,
			HttpServletRequest request){
		String result = null;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile(fileParameterName);
		if(file == null){
			return result;
		}
		//save temporary file
		String localFilePath = rootDir;
		String localFile = file.getOriginalFilename();
		if(localFile == "" || localFile == null){
			return result;
		}
		InputStream ins = null;
		OutputStream fos = null;
		try{
			request.setCharacterEncoding("utf-8");
			ins = file.getInputStream();
			result = "/" + localFile;
			String localFileName = localFilePath + result;
			fos = new FileOutputStream(localFileName);
			try{
				int readed = 0;
				byte[] buffer = new byte[8192];
				while((readed = ins.read(buffer, 0, 8192)) != -1){
					fos.write(buffer, 0, readed);
				}
			}catch(Exception e){
				e.printStackTrace();
				result = null;
			}
		}catch(Exception e){
			e.printStackTrace();
			result = null;
		}finally{
			if(ins != null){
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				ins=null;
			}
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				fos = null;
			}
		}
		return result; 
	}
    
    
    /**
	 * 
	 * @param url
	 * @param content
	 * @param endCode  编码格式
	 * @return
	 */
    public static String postUrl(String url, String content) throws Exception{
        String postresult = "";
        try {
          URL urlmy = new URL(url);
          HttpURLConnection connection = (HttpURLConnection)urlmy.openConnection();
          connection.setRequestProperty("Content-Length", Integer.toString(content.length()));
          connection.setRequestProperty("Content-type", "application/x-java-serialized-object");
          connection.setConnectTimeout(TIMEOUT_CONNECTION);
          connection.setReadTimeout(TIMEOUT_READ);
          connection.setRequestMethod("POST");
          connection.setDoOutput(true);
          connection.setDoInput(true);

          BufferedOutputStream outt = new BufferedOutputStream(connection.getOutputStream());
          StringBuffer buffer = new StringBuffer(content.length());
          buffer.append(content);
          outt.write(buffer.toString().getBytes("UTF-8"));
          outt.flush();
          outt.close();

          log.info("响应代码：" + connection.getResponseCode());
          BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), "UTF-8"));
          String inputLine = null;
          while ((inputLine = in.readLine()) != null) {
            postresult = postresult + inputLine;
          }
          in.close();
        }
        catch (Exception ex) {
        	ex.printStackTrace();
        	throw new Exception(ex);
        }
        return postresult;
      }

    /*
     * 发送json格式
     */
    public static String postUrlJsonParam(JSONObject jsonParam, String url) {
        String result = "";
        org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        StringEntity postEntity = new StringEntity(jsonParam.toString(), Charset.forName("utf-8"));// 解决中文乱码问题
        // 设置类型
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setEntity(postEntity);
        // 根据默认超时限制初始化requestConfig
        // 请求器的配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_READ)
                .setConnectTimeout(TIMEOUT_CONNECTION).build();

        httppost.setConfig(requestConfig);
        try {

            HttpResponse response;
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity, "UTF-8");
        } catch (ConnectionPoolTimeoutException e) {
            log.info("http get throw ConnectionPoolTimeoutException(wait time out)");

        } catch (ConnectTimeoutException e) {
            log.info("http get throw ConnectTimeoutException");
        } catch (SocketTimeoutException e) {
            log.info("http get throw SocketTimeoutException");

        } catch (Exception e) {
            log.info("http get throw Exception");

        } finally {
            httppost.abort();
        }

        return result;
    }

	/*
     * 发送json格式
     */
	public static String postUrlJsonParam(JSONObject jsonParam, String url,Map<String,String> heads) {
		String result = "";
		org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);

		StringEntity postEntity = new StringEntity(jsonParam.toString(),Charset.forName("utf-8"));//解决中文乱码问题

		if(heads.size()>0){
			Set<String> keys = heads.keySet();
			for(String key : keys){
				httppost.addHeader(key,heads.get(key));
			}
		}

		// 设置类型
		httppost.setEntity(postEntity);
		// 根据默认超时限制初始化requestConfig
		// 请求器的配置
		// RequestConfig requestConfig =
		// RequestConfig.custom().setSocketTimeout(TIMEOUT_READ).setConnectTimeout(TIMEOUT_CONNECTION)
		// .build();
		//
		// httppost.setConfig(requestConfig);
		try {

			HttpResponse response;
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();

			result = EntityUtils.toString(entity, "UTF-8");
		} catch (ConnectionPoolTimeoutException e) {
			log.info("http get throw ConnectionPoolTimeoutException(wait time out)");

		} catch (ConnectTimeoutException e) {
			log.info("http get throw ConnectTimeoutException");
		} catch (SocketTimeoutException e) {
			log.info("http get throw SocketTimeoutException");

		} catch (Exception e) {
			log.info("http get throw Exception");

		} finally {
			httppost.abort();
		}

		return result;
	}

}
